package com.yoomiito.app.ui.my.repurchase;

import android.content.Intent;
import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.yoomiito.app.Constant;
import com.yoomiito.app.base.App;
import com.yoomiito.app.base.AppConfig;
import com.yoomiito.app.base.BaseActPresenter;
import com.yoomiito.app.base.WebViewActivity;
import com.yoomiito.app.model.bean.AddressInfo;
import com.yoomiito.app.model.bean.MaintainGoods;
import com.yoomiito.app.model.order.PayResultInfo;
import com.yoomiito.app.net.YmApi;
import com.yoomiito.app.pay.PayTypeUtils;
import com.yoomiito.app.ui.order.list.OrderActivity;
import com.yoomiito.app.utils.AllCode;
import com.yoomiito.app.utils.EventMessage;
import com.yoomiito.app.utils.L;
import com.yoomiito.app.utils.NetworkUtils;
import com.yoomiito.app.utils.YMToast;

import org.json.JSONException;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;

import cn.droidlover.xdroidmvp.cache.SharedPref;
import cn.droidlover.xdroidmvp.log.XLog;
import cn.droidlover.xdroidmvp.net.ApiException;
import cn.droidlover.xdroidmvp.net.ApiSubscriber;
import cn.droidlover.xdroidmvp.net.BaseModel;
import cn.droidlover.xdroidmvp.net.XApi;
import cn.droidlover.xdroidmvp.router.Router;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RepurchasePresenter extends BaseActPresenter<RepurchaseActivity> {

    public RepurchasePresenter(AppConfig appConfig) {
        super(appConfig);
    }


    public void getAddress() {
        YmApi.getYmService()
                .getAddressList(1)
                .compose(getV().bindToLifecycle())
                .compose(XApi.getApiTransformerData())
                .compose(XApi.getScheduler())
                .subscribe(new ApiSubscriber<List<AddressInfo>>() {
                    @Override
                    public void onSuccess(List<AddressInfo> addressInfo) {
//                        if (addressInfos.size()==0){

                        if (addressInfo.size() == 0) {
                            getV().showAddressView(new AddressInfo());
                        } else {
                            int j = 0;
                            for (int i = 0; i < addressInfo.size(); i++) {
                                if (TextUtils.equals(addressInfo.get(i).getIsDefault(), "1")) {
                                    j = i;
                                }
                            }
                            getV().showAddressView(addressInfo.get(j));
                        }


//                        }else {
//                            for (AddressInfo addressInfo:addressInfos) {
//                                if ("1".equals(addressInfo.getIsDefault())){
//                                    getV().showAddressView(addressInfo);
//                                }
//                            }
//                        }
                    }

                    @Override
                    public void onFail(ApiException error) {
                        getV().dismissLoading();
                        if (!TextUtils.isEmpty(error.getMsg())) {
                            YMToast.showText(error.getMsg());
                        }
                    }
                });
    }

    public void confirmOrder() {
        YmApi.getYmService()
                .mugwortReplenishList(1)
                .compose(getV().bindToLifecycle())
                .compose(XApi.getApiTransformerData())
                .compose(XApi.getScheduler())
                .subscribe(new ApiSubscriber<MaintainGoods>() {
                    @Override
                    public void onSuccess(MaintainGoods addressInfo) {

                        getV().setData(addressInfo);
                    }

                    @Override
                    public void onFail(ApiException error) {
                        getV().dismissLoading();
                        if (!TextUtils.isEmpty(error.getMsg())) {
                            YMToast.showText(error.getMsg());
                        }
                    }
                });
    }

    public void createOrder(String goodsList, String consignee, String provinceId,
                            String cityId, String countryId, String tel, String address,
                            String note) {
        if (NetworkUtils.checkNetPermission(getV())) {
            return;
        }
        LinkedHashMap<String, Object> params = new LinkedHashMap<>();
        params.put("province", provinceId);
        params.put("city", cityId);
        params.put("county", countryId);
        params.put("address", address);
        params.put("consignee", consignee);
        params.put("mobile", tel);
        if (!TextUtils.isEmpty(note)) {
            params.put("note", note);
        }
        params.put("goodsList", goodsList);
        RequestBody body = RequestBody.create(YmApi.JSON, JSONObject.toJSONString(params));
        YmApi.getYmService()
                .cOrder(body)
                .compose(getV().bindToLifecycle())
                .compose(XApi.getApiTransformerNoData())
                .compose(XApi.getScheduler())
                .subscribe(new ApiSubscriber<BaseModel>(handleException()) {
                    @Override
                    public void onSuccess(BaseModel baseModel) {
                        YMToast.showText("您已提货成功，等待发货");
                        Router.newIntent(getV())
                                .to(OrderActivity.class)
                                .putInt("select", 2)
                                .putInt(Constant.TYPE,1)
                                .launch();
                        getV().finish();
                    }

                    @Override
                    public void onFail(ApiException error) {

                    }
                });
    }


    public void getInterface(String url,String consignee, String provinceId,
                             String cityId, String countryId, String areaName, String tel, String address,
                             String note, int num,int addressType,int type,int payType,String good) {
        LinkedHashMap<String, Object> params = new LinkedHashMap<>();
        params.put("consignee", consignee);
        params.put("goodsList", good);
        params.put("payType", payType);
        params.put("type", type);
        params.put("addressType", addressType);
        if(addressType == 1){
            params.put("city", cityId);
            params.put("province", provinceId);
            params.put("county", countryId);
            params.put("area_name", areaName);
            params.put("address", address);
            params.put("mobile", tel);
        }
        params.put("exchangeNum",0);
        params.put("systemType",1);
        L.e("参数:" + params.toString());
        RequestBody body = RequestBody.create(YmApi.JSON, JSONObject.toJSONString(params));
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(YmApi.BaseUrl + url)
                .addHeader("Authorization", SharedPref.getInstance(App.getInstance()).getString(Constant.TOKEN, ""))
                .header("Platform", "")
                .header("Site","app_mugwort_android")
                .post(body)
                .build();
        Call call = client.newCall(request);
        XLog.e(YmApi.BaseUrl + url + "===");
        call.enqueue(new Callback() {
            // 2
            @Override
            public void onFailure(Call call, IOException e) {
                //Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                getV().dismissLoading();
                EventMessage eventMessage = new EventMessage();
                eventMessage.setCode(AllCode.Fail);
                getV().payResult(eventMessage);
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                if (getV() == null) return;
                getV().dismissLoading();
                // 3
                try {
                    org.json.JSONObject obj = new org.json.JSONObject(response.body().string());
                    String data = obj.getString("data");
                    if (obj.getInt("code") == 200) {
                        PayResultInfo payResultInfo = new Gson().fromJson(data, PayResultInfo.class);
                        if ("accountpay".equals(payResultInfo.getPay_type()) || "offlinepay".equals(payResultInfo.getPay_type())) {
                            EventMessage eventMessage = new EventMessage();
                            eventMessage.setCode(AllCode.Success);
                            getV().payResult(eventMessage);
                        } else if("fast_pay".equals(payResultInfo.getPay_type())){
                            Intent intent = new Intent(getV(), WebViewActivity.class);
                            intent.putExtra(Constant.DATA, payResultInfo.getData().getFastPay_order());
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            getV().startActivity(intent);
                        } else {
                            getV().dismissLoading();
                            getV().pay_type = payResultInfo.getPay_type();
                            if ("wxpay".equals(payResultInfo.getPay_type())) {
                                PayTypeUtils.wxPay(payResultInfo.getData());
                            } else {
                                if("alipay_h5".equals(payResultInfo.getPay_type())){
                                    getV().setShow();
                                    Intent intent = new Intent(getV(), WebViewActivity.class);
                                    intent.putExtra(Constant.DATA, payResultInfo.getData().getAlipay_order());
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    getV().startActivity(intent);

                                }else{
                                    PayTypeUtils.aliPay(getV(), payResultInfo.getData().getAlipay_order());
                                }
                            }
                        }
                    }else{
                        EventMessage eventMessage = new EventMessage();
                        eventMessage.setCode(AllCode.Fail);
                        getV().payResult(eventMessage);
                        getV().finish();
                        getV().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    YMToast.showText(obj.getString("msg") );
                                } catch (JSONException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        });
                    }
                    XLog.e("======="+response.body().string());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });


    }


}
